'use strict'

function init() {
  window.page = new Page()
  page.dom.content_box.style.backgroundColor = page.data.theme_color
  page.getAllData()
}

setTimeout(init)

function Page() {
  this.dom = {
    content_box: $('#content_box'),
    page_container: $('#page_container'),
    scroll_view: $('#scroll_view'),
    idiom_box: $('#idiom_box'),
    idiom_text: $('#idiom_text'),
    verse_title: $('#verse_title'),
    verse_content: $('#verse_content'),
    no_more: $('#no_more'),
  }

  this.data = {
    verse_list: [],
    nice_verse: {},
    idiom: {},
    pc_show: false, // 是否显示page-container
    theme_color: '',
    page: 0,
    page_size: 15,
    on_more: false,
  }

  this.data_proxy = new Proxy(this.data, {
    set(target, key, value) {
      switch (key) {
        case 'pc_show':
          page.dom.page_container.classList.toggle('out-by-bottom', !value)
          break
        case 'no_more':
          if (value) {
            page.dom.no_more.style.display = 'none'
          }
          break
        case 'idiom':
          page.dom.idiom_text.innerText = value.text
          page.dom.idiom_box.style.display = 'flex'
          break
        case 'nice_verse':
          page.dom.verse_title.innerText = value.title
          page.dom.verse_content.innerText = value.text_pure
          break
        case 'verse_list':
          const current_length = target.verse_list.length
          page.dom.no_more.insertAdjacentHTML(
            'beforebegin',
            value.slice(current_length).reduce((p, c, i) => (p += `<div class="cell" data-index="${current_length + i}">${c.title}</div>`), '')
          )
          break
      }
      target[key] = value
      return true
    },
  })

  const color = window.config.theme.color
  this.data.theme_color = color[~~(Math.random() * color.length)]
}

Page.prototype.getAllData = function () {
  loading()
  Promise.all([
    this.getVerseList({
      page: this.data.page,
      page_size: this.data.page_size,
    }),
    this.getIdiom(),
  ])
    .then(([{ verse_list, nice_verse }, idiom]) => {
      this.data_proxy.idiom = idiom
      this.data_proxy.verse_list = verse_list
      this.data_proxy.nice_verse = nice_verse
    })
    .finally(unloading)
}

Page.prototype.getVerseList = function ({ page, page_size }) {
  if (this.data.no_more) return Promise.resolve()
  return av
    .read('PSNiceVerse', (q) => {
      q.limit(page_size)
      q.skip(page * page_size)
      q.descending('updateAt')
    })
    .then((ret) => {
      let verse_list = [
        ...this.data.verse_list,
        ...ret.map((i_s) => {
          let i = i_s.toJSON()
          i.title = i.title.replace(/(.*)(《.*)/, '$2$1')
          i.text_pure = i.text.replace(/，|。|？|；|、！|：|“|”|《|【|】|》/g, ' ')
          return i
        }),
      ]
      let result = {
        verse_list,
        nice_verse: undefined,
      }
      if (!page) {
        result.nice_verse = verse_list[0] || {}
      }
      this.data.page += 1
      this.data_proxy.no_more = !!(verse_list.length % page_size) // 如果是page_size的个数，就没有更多了
      return result
    })
}

Page.prototype.getIdiom = function () {
  return av
    .read('PSIdiom', (q) => {
      q.limit(1)
    })
    .then((ret) => {
      return ret[0].toJSON()
    })
}

Page.prototype.clickVerseTitle = function (e) {
  this.data_proxy.pc_show = true
}

Page.prototype.clickPageContainer = function () {
  this.data_proxy.pc_show = false
}

Page.prototype.clickVerseText = function () {
  return
}

Page.prototype.clickVerseItem = function (e) {
  e.stopPropagation()
  if (e.target.classList.contains('no-more')) {
    this.getVerseList({ page: this.data.page, page_size: this.data.page_size }).then((ret) => {
      Object.keys(ret).forEach((key) => {
        const value = ret[key]
        if (value) this.data_proxy[key] = value
      })
    })
    return
  }
  let index = e.target.dataset.index || 0
  this.data_proxy.nice_verse = this.data.verse_list[index]
  this.data_proxy.pc_show = false
}

Page.prototype.clickIdiom = function () {
  const idiom = this.data.idiom
  let content = idiom.content
  new Promise((resolve) => {
    if (content) resolve(content)
    else {
      this.getBaiduHanyuContent({
        text: idiom.text,
      }).then((ret) => {
        const match = ret.match(/id=\"basicmean-wrapper\"[\s\S]*?p>([\s\S]*?)<\/p>/)
        const content = match ? ret.match(/id=\"basicmean-wrapper\"[\s\S]*?p>([\s\S]*?)<\/p>/)[1].replace(/\s|\n/g, '') : `未匹配到释义`
        if (match) {
          this.$http.wxCloudFunction({
            query: `db.collection('Idiom').doc('${idiom._id}').update(${JSON.stringify({
              data: {
                content,
              },
            })})`,
          })
        }
        resolve(content)
      })
    }
  }).then((content) => {
    alert(idiom.text)
    if (!idiom.content) {
      this.$set(this.data, idiom, 'content', content)
    }
  })
}

Page.prototype.getBaiduHanyuContent = function ({ text, key_word = '释义' }) {
  if (!text) return Promise.reject('no text for BaiduHanyu')
  loading()
  return uni
    .request({
      url: 'https://hanyu.baidu.com/s?wd=' + text,
    })
    .then((ret) => {
      if (ret[0]) return {}
      return ret[1].data || ''
    })
    .finally(unloading)
}

const demp_template_string = document.querySelector('#demo_tempalte').innerHTML.temp2str({
  p: 'im p',
  href: 'https://www.baidu.com',
  a: 'im a',
})

console.log({ demp_template_string })

lf.setItem('test_value', "localforage's i am test value.").then((ret) => {
  console.log(ret)
  lf.getItem('test_value').then(console.log)
})
